package com.yunc.modules.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunc.common.oss.QiniuCloudStorageService;
import com.yunc.common.utils.QrcodeUtil;
import com.yunc.common.utils.R;
import com.yunc.common.wx.WxMpConfiguration;
import com.yunc.modules.cms.entity.Question;
import com.yunc.modules.cms.entity.QuestionSubject;
import com.yunc.modules.cms.entity.QuestionSubjectSelect;
import com.yunc.modules.cms.mapper.QuestionMapper;
import com.yunc.modules.cms.service.IQuestionService;
import com.yunc.modules.cms.service.IQuestionSubjectSelectService;
import com.yunc.modules.cms.service.IQuestionSubjectService;
import me.chanjar.weixin.common.api.WxConsts;
import org.apache.commons.lang3.StringUtils;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

/**
 * 问卷管理表 service实现
 *
 * @author concong tao
 * @since 2019-01-31
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

    @Autowired
    private IQuestionSubjectService questionSubjectService;
    @Autowired
    private IQuestionSubjectSelectService questionSubjectSelectService;
    @Autowired
    private QiniuCloudStorageService qiniuCloudStorageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveQuestion(HttpServletRequest request,  Question question) {
        question.setCreateTime(new Date());
        boolean flag = this.save(question);
        if (!flag) {
            return R.error();
        }
        // 获取id
        Long questionId = question.getId();
        // 生成二维码
        URL requestURL = null;
        try {
            requestURL = new URL(request.getRequestURL().toString());
            String url = WxMpConfiguration.getMpServices().get("wx8dde7415f5db603c")
                    .oauth2buildAuthorizationUrl(
                            String.format("%s://%s/wx/redirect/%s/question", requestURL.getProtocol(), requestURL.getHost(), "wx8dde7415f5db603c"),
                            WxConsts.OAuth2Scope.SNSAPI_USERINFO, questionId.toString());
            question.setWxUrl(url);
            String qrcode = QrcodeUtil.qrcode(url);
            question.setQrCode(qrcode);
            boolean updateFlag = this.updateById(question);
            if (!updateFlag) {
                return R.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        String subjectJson = question.getSubjectJson();
        if (StringUtils.isEmpty(subjectJson)) {
            return R.ok();
        }
        return questionSubjectService.saveQuestionSubject(questionId, subjectJson);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateQuestion(Question question) {
        boolean flag = this.updateById(question);
        if (!flag) {
            return R.error();
        }
        String subjectJson = question.getSubjectJson();
        if (StringUtils.isEmpty(subjectJson)) {
            return R.ok();
        }
        Long questionId = question.getId();
        // 删除现有数据
        questionSubjectService.remove(new QueryWrapper<QuestionSubject>().eq("question_id", questionId));
        questionSubjectSelectService.remove(new QueryWrapper<QuestionSubjectSelect>().eq("question_id", questionId));
        return questionSubjectService.saveQuestionSubject(questionId, subjectJson);
    }
}
